package com.hong.service_oss.controller;


import com.hong.fy_common_commomutil.common.result.Result;
import com.hong.service_oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Api(tags = "文件上传下载")
@RestController
@RequestMapping("/api/file")
public class FileApiController {

    @Autowired
    private FileService fileService;

    @Value("${fy.path}")
    private String baseUrl;


    //上传文件到阿里云oss
    @ApiOperation(value = "上传文件到阿里云oss")
    @PostMapping("/oss/fileUpload")
    public Result fileUploadOss(@RequestParam("file") MultipartFile file) {
        //获取上传文件
        if (file == null) {
            return Result.fail("文件为空");
        }
        String url = fileService.uploadOss(file);
        return Result.ok(url);
    }

    //上传文件到本地服务器
    @ApiOperation(value = "上传文件到本地服务器")
    @PostMapping("/local/fileUpload")
    public Result fileUploadLocal(@RequestParam("file") MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        //获取上传文件
        if (file == null) {
            return Result.fail("文件为空");
        }
        String url = fileService.uploadLocal(file);
        return Result.ok(url);
    }

    //文件下载
    @ApiOperation(value = "文件下载")
    @GetMapping("/download")
    public void download(String name , HttpServletResponse response) {
        try{
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(baseUrl + name));

            //输出流，通过输出流将文件内容写到客户端，在浏览器中显示
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");//设置响应类型

            int len= 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) { //读取文件内容
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
